package org.jlamp.boot.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpResponse;

/**
 * @author zhangcs
 */
public class JlampClientHandler extends SimpleChannelInboundHandler<FullHttpResponse> {

    private ChannelHandlerContext ctx;

    private ChannelPromise promise;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        this.ctx = ctx;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpResponse webSocketFrame) throws Exception {
        promise.setSuccess();
    }

    public synchronized ChannelPromise send(String msg) {
        while (ctx != null) {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                // ignore
            }
        }

        promise = ctx.newPromise();
        ctx.writeAndFlush(msg);
        return promise;
    }


}
